<template>
  <div class="detail-page">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>图书详情</span>
          <div>
            <el-button type="primary" @click="handleAddToCart">加入购物车</el-button>
            <el-button @click="goBack">返回列表</el-button>
            <el-button @click="goCenter">个人中心</el-button>
          </div>
        </div>
      </template>

      <el-descriptions :column="1" border v-if="detail">
        <el-descriptions-item label="封面">
          <el-image :src="detail.cover_image" style="width:120px;height:150px" fit="cover" />
        </el-descriptions-item>
        <el-descriptions-item label="书名">{{ detail.title }}</el-descriptions-item>
        <el-descriptions-item label="作者">{{ detail.author }}</el-descriptions-item>
        <el-descriptions-item label="出版社">{{ detail.publisher }}</el-descriptions-item>
        <el-descriptions-item label="分类">{{ detail.category }}</el-descriptions-item>
        <el-descriptions-item label="价格">¥ {{ Number(detail.price).toFixed(2) }}</el-descriptions-item>
        <el-descriptions-item label="简介">{{ detail.description }}</el-descriptions-item>
      </el-descriptions>

      <el-empty description="暂无数据" v-else />

      <el-divider />

      <div class="reviews">
        <div class="reviews-header">
          <h3>图书评价</h3>
        </div>
        <div class="review-form">
          <el-input
            v-model="newReview.comment"
            type="textarea"
            :rows="3"
            placeholder="写下你的评价..."
          />
          <div style="margin-top: 8px; text-align: right;">
            <el-button type="primary" @click="submitReview">发布评价</el-button>
          </div>
        </div>
        <el-divider />
        <el-table :data="reviews" border>
          <el-table-column type="index" width="60" />
          <el-table-column prop="user" label="用户" width="160" />
          <el-table-column prop="rating" label="评分" width="100" />
          <el-table-column prop="comment" label="内容" />
        </el-table>
        <div class="pager">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :page-size="reviewQuery.size"
            :current-page="reviewQuery.page"
            @current-change="onReviewPageChange"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { fetchBookDetail, fetchBookReviews, addBookReview, addToCart } from '@/api/book'

const route = useRoute()
const router = useRouter()
const detail = ref<any>(null)
const reviews = ref<any[]>([])
const total = ref(0)
const reviewQuery = ref<{ page: number; size: number }>({ page: 1, size: 5 })
const newReview = ref<{ comment: string; rating: number }>({ comment: '', rating: 5 })

const loadDetail = async () => {
  try {
    const id = route.params.id as string
    const res = await fetchBookDetail(id)
    const data = res.data || {}
    detail.value = data.book_detail || data
  } catch (e: any) {
    ElMessage.error(e.response?.data?.message || '加载详情失败')
  }
}

const loadReviews = async () => {
  try {
    const id = route.params.id as string
    const res = await fetchBookReviews(id, reviewQuery.value)
    const data = res.data || {}
    reviews.value = Array.isArray(data.review_list) ? data.review_list : (Array.isArray(data) ? data : [])
    total.value = Number(data.total || 0)
  } catch (e: any) {
    ElMessage.error(e.response?.data?.message || '加载评价失败')
  }
}

const onReviewPageChange = (p: number) => {
  reviewQuery.value.page = p
  loadReviews()
}

const submitReview = async () => {
  try {
    const id = route.params.id as string
    if (!newReview.value.comment) {
      ElMessage.warning('请输入评价内容')
      return
    }
    await addBookReview(id, newReview.value)
    ElMessage.success('评价已提交')
    newReview.value.comment = ''
    await loadReviews()
  } catch (e: any) {
    ElMessage.error(e.response?.data?.message || '提交失败')
  }
}

const goBack = () => {
  router.push('/books')
}

const goCenter = () => {
  router.push('/center')
}

const handleAddToCart = async () => {
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      router.push({ path: '/login', query: { redirect: router.currentRoute.value.fullPath } })
      return
    }
    const id = (detail.value && (detail.value.book_id || detail.value.id))
    if (!id) return
    await addToCart({ book_id: id, quantity: 1 })
    ElMessage.success('已加入购物车')
  } catch (e: any) {
    ElMessage.error(e.response?.data?.message || '加入购物车失败')
  }
}

onMounted(() => {
  loadDetail()
  loadReviews()
})
</script>

<style scoped>
.detail-page { padding: 20px; }
.card-header { display: flex; align-items: center; justify-content: space-between; }
</style>
